package com.tomtop.core.code;

public final class Sequence {
	private volatile static String empty = TransforCodeString.serialize(0L);
	private volatile static byte cycle = 0;
	private volatile static String cycleStr = empty;
	private volatile static String hostIdStr = empty + empty;
	private volatile static long sequence = -1;
	private static long oldRunTime = 60 + System.currentTimeMillis() / 1000 / 60 / 60 * 60;

	public final static String generate() {
		long runTime = System.currentTimeMillis() / 60000;
		if (oldRunTime <= runTime) {
			oldRunTime = runTime / 60 * 60 + 60;
			sequence = -1;
			cycle = (byte) (++cycle % 64);
			cycleStr = TransforCodeString.serialize((long) cycle);
		}
		StringBuffer buffer = new StringBuffer().append(hostIdStr) // 2位
				.append(cycleStr); // 1位
		addFormat(buffer, TransforCodeString.serialize(runTime), 6); // 6位
		buffer.append('-');
		addFormat(buffer, TransforCodeString.serialize(++sequence), 6); // 7位
		return buffer.toString();
	}

	private static void addFormat(StringBuffer buffer, String str, int length) {
		int addNum = length - str.length();
		if (addNum > 0)
			for (int i = 0; i < addNum; i++) {
				buffer.append(empty);
			}
		buffer.append(str);
	}

	public static short getHostId() {
		long hostId = TransforCodeString.deserialize(hostIdStr);
		return (short) hostId;
	}

	public static void setHostId(short hostId) {
		Sequence.hostIdStr = TransforCodeString.serialize((long) hostId);
		if (Sequence.hostIdStr.length() == 1)
			Sequence.hostIdStr = empty + Sequence.hostIdStr;
	}
}
